"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : DMS分布式锁
Case Name   : 进入死锁状态，用户主动cancel任意事务，另一事务执行成功
Create At   : 2023/4/20
Owner       : opentestcase033
Description :
    1.创建测试表
    2.主节点开启事务A修改表1，主节点执行删除表2，结束删除表事务
    3.备节点开启事务B查询表2，查询表1
    4.清理环境
Expect:
    1.成功
    2.成功，删表2阻塞
    3.成功，查询表1阻塞
    4.成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 > Primary_SH.get_node_num(), '非1+2以上环境不执行')
class DmsOck(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.std_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.table1 = 't_dms_ock_0076_1'
        self.table2 = 't_dms_ock_0076_2'

    def test_dms_ock(self):
        text1 = '-----step1:创建测试表;expect:执行成功-----'
        self.log.info(text1)
        create_tb = f"drop table if exists {self.table1} cascade;" \
                    f"create table {self.table1}(" \
                    f"id int, name varchar, source number) with(segment=on);" \
                    f"insert into {self.table1} values(1,'haha',92);" \
                    f"drop table if exists {self.table2} cascade;" \
                    f"create table {self.table2}(" \
                    f"xid int, zroup varchar) with(segment=on);" \
                    f"insert into {self.table2} values(1, '一组');"
        create_res = self.pri_sh.execut_db_sql(create_tb)
        self.log.info(create_res)
        self.assertEqual(create_res.count(self.constant.CREATE_TABLE_SUCCESS),
                         2, f"执行失败:{text1}")
        self.assertEqual(create_res.count(self.constant.INSERT_SUCCESS_MSG), 2,
                         f"执行失败:{text1}")

        text2 = '-----step2:主节点开启事务A修改表1，主节点执行删除表2，退出会话;expect:成功，删表2阻塞-----'
        self.log.info(text2)
        sql_a = f'''begin;
        alter table {self.table1} rename to new_{self.table1};
        select pg_sleep(3);
        drop table {self.table2};'''
        self.log.info(sql_a)
        session1 = ComThread(self.pri_sh.execut_db_sql, args=(sql_a,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1)

        text3 = '-----step3:备节点开启事务B查询表2 1;expect:成功，查询表1阻塞-----'
        self.log.info(text3)
        sql_b = f'''begin;
        select * from {self.table2};
        select pg_sleep(3);
        select * from {self.table1};
        end;'''
        self.log.info(sql_b)
        session2 = ComThread(self.std_sh.execut_db_sql, args=(sql_b,))
        session2.setDaemon(True)
        session2.start()
        time.sleep(3)
        self.log.info("pg_terminate_backend函数结束session1语句")
        res = self.pri_sh.execut_db_sql(
            f"select pid,pg_terminate_backend(pid) from pg_stat_activity "
            f"where state = 'active' and query = 'drop table {self.table2};';")
        self.log.info(res)
        session1.join(20)
        session2.join(20)
        res_a = session1.get_result()
        self.log.info(f'session1_results: {res_a}')
        res_b = session2.get_result()
        self.log.info(f'session2_results: {res_b}')
        self.assertIn(self.constant.ALTER_TABLE_MSG, res_a, f"执行失败:{text2}")
        self.assertIn('FATAL:  terminating connection due to '
                      'administrator command', res_a, f"执行失败:{text2}")
        self.assertIn('1 | 一组', res_b, f"执行失败{text3}")
        self.assertIn('1 | haha |     92\n(1 row)', res_b, f"执行失败{text3}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, res_b, f"执行失败{text3}")

    def tearDown(self):
        text4 = '-----step4:清理环境 expect:成功-----'
        self.log.info(text4)
        stop_res = self.pri_sh.exec_cm_ctl('stop')
        self.log.info(stop_res)
        start_res = self.pri_sh.exec_cm_ctl('start')
        self.log.info(start_res)
        time.sleep(10)
        drop_tb_res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.table1} cascade;"
            f"drop table if exists {self.table2} cascade;")
        self.log.info(drop_tb_res)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS,
                      drop_tb_res, f"删表失败:{text4}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
